//
//  MJRefresh.swift
//  OC-Swift
//
//  Created by 陆文宇 on 2017/2/14.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit

var MJRefreshHeaderKey: String = ""
var MJRefreshFooterKey: String = ""
var MJRefreshReloadDataClosureKey: String = ""

extension UIScrollView {
        
    var mj_header: MJRefreshHeader? {
        set {
            if newValue !== self.mj_header {
                self.mj_header?.removeFromSuperview()
                if let header = newValue {
                    insertSubview(header, at: 0)
                }
                
                willChangeValue(forKey: "mj_header")
                objc_setAssociatedObject(self, &MJRefreshHeaderKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
                didChangeValue(forKey: "mj_header")
            }
        }
        
        get {
            return objc_getAssociatedObject(self, &MJRefreshHeaderKey) as? MJRefreshHeader
        }
    }
    
    var mj_footer: MJRefreshFooter? {
        set {
            if newValue != self.mj_footer {
                self.mj_footer?.removeFromSuperview()
                if let footer = newValue {
                    insertSubview(footer, at: 0)
                }
                
                willChangeValue(forKey: "mj_footer")
                objc_setAssociatedObject(self, &MJRefreshFooterKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
                didChangeValue(forKey: "mj_footer")
            }
        }
        
        get {
            return objc_getAssociatedObject(self, &MJRefreshFooterKey) as? MJRefreshFooter
        }
    }
    
    var mj_totalDataCount: Int {
        var totalCount: Int = 0
        if self is UITableView {
            let tableView: UITableView = self as! UITableView
            
            for section in 0 ..< tableView.numberOfSections {
                totalCount += tableView.numberOfRows(inSection: section)
            }
        } else if self is UICollectionView {
            let collectionView: UICollectionView = self as! UICollectionView
            
            for section in 0 ..< collectionView.numberOfSections {
                totalCount += collectionView.numberOfItems(inSection: section)
            }
        }
        return totalCount
    }
    
    var mj_reloadDataClosure: ((Int) -> Void)? {
        set {
            willChangeValue(forKey: "mj_reloadDataClosure")
            objc_setAssociatedObject(self, &MJRefreshReloadDataClosureKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
            didChangeValue(forKey: "mj_reloadDataClosure")
        }
        
        get {
            return objc_getAssociatedObject(self, &MJRefreshReloadDataClosureKey) as? (Int) -> Void
        }
    }
    
}
